package com.ghsc.ghxc.jsb.ui.message.activity

import android.os.Bundle
import android.text.*
import android.view.View
import android.widget.EditText
import com.cn.appcore.base.BaseVMActivity
import com.cn.appcore.ext.getCompatColor
import com.cn.appcore.ext.gone
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.setSingleClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.ext.visible
import com.cn.appcore.utils.GsonUtil
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.databinding.ActivityRedExtensionBinding
import com.ghsc.ghxc.jsb.ui.message.view.PayPwdCodePopViiew
import com.ghsc.ghxc.jsb.ui.message.view.RedTypePopupView
import com.ghsc.ghxc.jsb.utils.OnlyOneEditText
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import java.io.UnsupportedEncodingException
import java.math.BigDecimal
import java.net.URLEncoder
import java.nio.charset.StandardCharsets


/**
 * 项目：GuoHuaMall
 * 包名：com.ghsc.ghxc.ui.message.activity
 * 类名：RedExtensionActivity
 * 创建时间：2023/8/3 12:07
 * 创建人 @author： xiaolin
 * 描述 ：Todo...发红包
 */
class RedExtensionActivity   : BaseVMActivity<RedExtensionViewModel, ActivityRedExtensionBinding>() {
    override fun attachLayoutRes(): Int {
        return R.layout.activity_red_extension
    }

    override fun initBar() {
        super.initBar()
        mImmersionBar!!.statusBarDarkFont(true).init()
    }

    override fun attachVMClass(): Class<RedExtensionViewModel>? {
        return RedExtensionViewModel::class.java
    }


    var  bundle  : Bundle?=null
    var type:Int =-1
    var targetId:String =""

    var redType:Int =1  //类型 1 拼手气 2 普通



    var maxCount=0  //最多数量


    var service_charge_rate:Double=0.0


    //是否需要校验短信验证码
    var isSendCode =false
    //是否需要校验支付密码
    var isSendPassword =false

    override fun onResume() {
        super.onResume()


        mViewModel.onRedIndexDataMethod("")
    }

    override fun initView() {
        bundle=intent.extras
        type=bundle!!.getInt("type")
        targetId=bundle!!.getString("targetId","")
        loge("targetId="+targetId +"type="+type)
        binding.bar.topTitle.text="发红包"
        binding.run {
            bar.topLeftView.setSingleClickListener {
                hideKeyboard(etMoneyNumber)
                finish()
            }
        }

        onInitType(1)
        //个人红包
//        binding.etNum.setText("1")

//        val textChange = TextChange()
//        binding.etNum.addTextChangedListener(textChange)
//        binding.etMoneyNumber.addTextChangedListener(textChange)
//        binding.etMoneyNumberAll.addTextChangedListener(textChange)
    }


    private fun  onInitType(index :Int){
        if (index ==1 ){
            binding.lltype1.visibility= View.VISIBLE
            binding.lltype2.visibility= View.GONE
            redType=1
            binding.tvType.text="拼手气红包"
        }else{
            binding.lltype1.visibility= View.GONE
            binding.lltype2.visibility= View.VISIBLE
            redType=2
            binding.tvType.text="普通红包"
        }
    }

    override fun initData() {
        super.initData()

        binding.etNum.inputType= InputType.TYPE_CLASS_NUMBER
        setEditTextOnlyDigits(binding.etNum)



        //允许输入小数
        binding.etMoneyNumberAll.setInputType(InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL)
        //限制输入的位数
        binding.etMoneyNumberAll.addTextChangedListener( OnlyOneEditText(binding.etMoneyNumberAll).setInputNum(4))


        //允许输入小数
        binding.etMoneyNumber.setInputType(InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL)
        //限制输入的位数
        binding.etMoneyNumber.addTextChangedListener( OnlyOneEditText(binding.etMoneyNumber).setInputNum(4))


        binding.etNum.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                loge("输入前的监听"+p0.toString().trim())

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                loge("输入变化的监听"+p0.toString().trim())




                if(redType==2){
                    if (!TextUtils.isEmpty(p0.toString().trim()) && !TextUtils.isEmpty(binding.etMoneyNumber.text.toString().trim())) {
                        val num =p0.toString().trim().toInt()
                        val money =binding.etMoneyNumber.text.toString().trim().toDouble()
                        if (num>0 && money>0) {

                            val price = (money * num)  +  ((money * num) * service_charge_rate)
                            binding.tvAll.text=  String.format("%.4f", price)
                            setState(price)

                        }else{
                            binding.tvAll.text="0.00"
                            binding.tvBtnNext.alpha = 0.5f
                            binding.tvBtnNext.isEnabled=false
                        }
                    }else{
                        binding.tvBtnNext.alpha = 0.5f
                        binding.tvBtnNext.isEnabled=false
                    }
                }else{
                    if (!TextUtils.isEmpty(binding.etMoneyNumberAll.text.toString().trim())){
                        val money =binding.etMoneyNumberAll.text.toString().trim().toDouble()
                        if ( money>0) {
                            val price = money  +  (money * service_charge_rate)
                            binding.tvAll.text= String.format("%.4f", price)
                            var numStr = binding.etNum.text.toString().trim()
                            if (!TextUtils.isEmpty(numStr)){
                                var num = numStr.toInt()
                                if (num>0){
                                    var number=price.toBigDecimal()
                                    val number2 = BigDecimal("0.01")
                                    if (number>= number2) {
                                        loge("当前true=")
                                        binding.tvBtnNext.alpha = 1f
                                        binding.tvBtnNext.isEnabled = true
                                        setState(price)
                                    }else{
                                        loge("当前false=")
                                        binding.tvBtnNext.alpha = 0.5f
                                        binding.tvBtnNext.isEnabled=false
                                    }
                                }else{
                                    binding.tvBtnNext.alpha = 0.5f
                                    binding.tvBtnNext.isEnabled=false
                                }
                            }else{
                                binding.tvBtnNext.alpha = 0.5f
                                binding.tvBtnNext.isEnabled=false
                            }

                        }else{
                            binding.tvAll.text="0.00"
                            binding.tvBtnNext.alpha = 0.5f
                            binding.tvBtnNext.isEnabled=false
                        }
                    }else{
                        binding.tvAll.text="0.00"
                        binding.tvBtnNext.alpha = 0.5f
                        binding.tvBtnNext.isEnabled=false
                    }
                }
            }

            override fun afterTextChanged(s: Editable?) {
                loge("输入后的监听"+s.toString().trim())
//                if (s.toString().startsWith("0") || s.toString() == "") {
//                    binding.etNum.setText("")
//                    binding.etNum.setSelection(0)
//                }


                if (!TextUtils.isEmpty(s.toString()))
                    if (s.toString().toInt() > maxCount){
                        binding.etNum.setText(maxCount.toString())
                        binding.etNum.setSelection(maxCount.toString().length)
                    }


            }

        })
        binding.etMoneyNumberAll.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(s: CharSequence, p1: Int, p2: Int, p3: Int) {
                if(redType==1){
                    if (!TextUtils.isEmpty(s.toString().trim())) {
                        val money =binding.etMoneyNumberAll.text.toString().trim().toDouble()
                        loge("输入后的监听onTextChanged"+money)
                        if ( money>0) {
                            val price = money  +  (money * service_charge_rate)
                            binding.tvAll.text= String.format("%.4f", price)
                            var numStr = binding.etNum.text.toString().trim()
                            if (!TextUtils.isEmpty(numStr)){
                                var num = numStr.toInt()
                                if (num>0){
                                    var number=(price/num).toBigDecimal()
                                    val number2 = BigDecimal("0.0001")
                                    if (number>= number2) {
                                        loge("当前true=")
                                        binding.tvBtnNext.alpha = 1f
                                        binding.tvBtnNext.isEnabled = true
                                        setState(price)
                                    }else{
                                        loge("当前false=")
                                        binding.tvBtnNext.alpha = 0.5f
                                        binding.tvBtnNext.isEnabled=false
                                    }
                                }else{
                                    binding.tvBtnNext.alpha = 0.5f
                                    binding.tvBtnNext.isEnabled=false
                                }
                            }else{
                                binding.tvBtnNext.alpha = 0.5f
                                binding.tvBtnNext.isEnabled=false
                            }

                        }else{
                            binding.tvAll.text="0.00"
                            binding.tvBtnNext.alpha = 0.5f
                            binding.tvBtnNext.isEnabled=false
                        }
                    }else{
                        binding.tvAll.text="0.00"
                        binding.tvBtnNext.alpha = 0.5f
                        binding.tvBtnNext.isEnabled=false
                    }
                }
            }

            override fun afterTextChanged(p0: Editable?) {
                loge("输入后的监听afterTextChanged"+p0)

            }

        })
        binding.etMoneyNumber.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(s: CharSequence?, p1: Int, p2: Int, p3: Int) {
                if(redType==2){
                    if (!TextUtils.isEmpty(s.toString().trim())) {
                        val money =binding.etMoneyNumber.text.toString().trim().toDouble()
                        loge("输入后的监听onTextChanged"+money)
                        if (!TextUtils.isEmpty(binding.etNum.text.toString().trim())){
                            val num =binding.etNum.text.toString().trim().toInt()
                            if (num>0 && money>0) {
                                val price = (money * num)  +  ((money * num) * service_charge_rate)
                                binding.tvAll.text= String.format("%.4f", price)
                                setState(price)
                            }else{
                                binding.tvAll.text="0.00"
                                binding.tvBtnNext.alpha = 0.5f
                                binding.tvBtnNext.isEnabled=false
                            }
                        }else{
                            binding.tvBtnNext.alpha = 0.5f
                            binding.tvBtnNext.isEnabled=false
                        }
                    }else{
                        binding.tvBtnNext.alpha = 0.5f
                        binding.tvBtnNext.isEnabled=false
                    }
                }
            }

            override fun afterTextChanged(p0: Editable?) {

            }

        })



    }



    private fun setState(price:Double){
        val hongbao =binding.usableHongbao.text.toString().toDouble()
        if (hongbao>price) {
            binding.tvBtnNext.alpha = 1.0f
            binding.tvBtnNext.isEnabled=true
        } else {
            binding.tvBtnNext.alpha = 0.5f
            binding.tvBtnNext.isEnabled=false
        }
    }

    override fun initClickListener() {
        super.initClickListener()
        binding.run {
            tvType.setSingleClickListener {
                //类型
                XPopup.Builder(this@RedExtensionActivity)
                    .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                    .customHostLifecycle(lifecycle)
                    .dismissOnTouchOutside(true)
                    .hasShadowBg(true)
                    .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                    .asCustom(
                        RedTypePopupView(
                            this@RedExtensionActivity,
                            type1Confirm = {
                                onInitType(1)
                            },
                            type2Confirm = {
                                onInitType(2)
                            },
                        )
                    )
                    .show()
            }
            binding.tvBtnNext.setSingleClickListener {

                var count=binding.etNum.text.toString().trim()
                if (TextUtils.isEmpty(count)) {
                    showToast("请输入红包个数")
                    return@setSingleClickListener
                }
                if (count.toInt()<=0) {
                    showToast("请输入红包个数")
                    return@setSingleClickListener
                }
                if (count.toInt() > maxCount){
                    showToast("红包最大数量不得超过"+maxCount+"个")
                    return@setSingleClickListener
                }
                if(redType==1){
                    //拼手气红包
                    var amount=binding.etMoneyNumberAll.text.toString().trim()
                    if (TextUtils.isEmpty(binding.etMoneyNumberAll.text.toString().trim())) {
                        showToast("请输入红包的总数量")
                        return@setSingleClickListener
                    }

                    var money=amount.toDouble()
                    if (money<=0) {
                        showToast("请输入红包的总数量")
                        return@setSingleClickListener
                    }

                    if(!isSendCode && !isSendPassword){
                        showLoading()
                        var moeo =""
                        if (TextUtils.isEmpty(binding.etContent.text.toString().trim()))
                            moeo="恭喜发财 大吉大利"
                        else{
                            try {
                                moeo = URLEncoder.encode(
                                    binding.etContent.text.toString().trim(),
                                    StandardCharsets.UTF_8.toString()
                                )
                            } catch (e: UnsupportedEncodingException) {
                                e.printStackTrace()
                            }
                        }
                        val map: HashMap<String, Any> = HashMap()
                        map["ptype"] = redType
                        map["count"] = count
                        map["amount"] = money
                        map["memo"] = moeo
                        map["cover"] = ""
                        map["paypassword"] = ""
                        map["im_type"] = 1
                        map["source_id"] = targetId
                        map["count_down"] = 0
                        map["single_price"] = money
                        map["code"] = ""
                        loge("发送红包"+GsonUtil.mapToJsonStr(map).toString())
                        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onSendPacketSubmitMethod(it1) }
                    }else{
                        XPopup.Builder(this@RedExtensionActivity)
                            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter  )
                            .customHostLifecycle(lifecycle)
                            .autoOpenSoftInput(true)
                            .moveUpToKeyboard(true)
                            .dismissOnTouchOutside(false)
                            .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                            .autoOpenSoftInput(true)
                            .asCustom(
                                PayPwdCodePopViiew(this@RedExtensionActivity,5,isSendCode,isSendPassword ,object :
                                    PayPwdCodePopViiew.SublickListener{
                                    override fun onAdopt(etCode: String, pwdStr: String) {
                                        loge("验证码="+etCode+"密码="+pwdStr)
                                        showLoading()
                                        var moeo =""
                                        if (TextUtils.isEmpty(binding.etContent.text.toString().trim()))
                                            moeo="恭喜发财 大吉大利"
                                        else{
                                            try {
                                                moeo = URLEncoder.encode(
                                                    binding.etContent.text.toString().trim(),
                                                    StandardCharsets.UTF_8.toString()
                                                )
                                            } catch (e: UnsupportedEncodingException) {
                                                e.printStackTrace()
                                            }
                                        }
                                        val map: HashMap<String, Any> = HashMap()
                                        map["ptype"] = redType
                                        map["count"] = count
                                        map["amount"] = money
                                        map["memo"] = moeo
                                        map["cover"] = ""
                                        map["paypassword"] = pwdStr
                                        map["im_type"] = 1
                                        map["source_id"] = targetId
                                        map["count_down"] = 0
                                        map["single_price"] = money
                                        map["code"] = etCode
                                        loge("发送红包"+GsonUtil.mapToJsonStr(map).toString())
                                        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onSendPacketSubmitMethod(it1) }
                                    }

                                })
                            )
                            .show()
                    }
                }else{
                    //普通红包
                    var amount=binding.etMoneyNumber.text.toString().trim()
                    if (TextUtils.isEmpty(amount)) {
                        showToast("请输入红包的单个金额")
                        return@setSingleClickListener
                    }
                    var money=amount.toDouble()
                    if (money<=0) {
                        showToast("请输入红包的单个金额")
                        return@setSingleClickListener
                    }


                    if(!isSendCode && !isSendPassword){
                        showLoading()
                        var moeo =""
                        if (TextUtils.isEmpty(binding.etContent.text.toString().trim()))
                            moeo="恭喜发财 大吉大利"
                        else{
                            try {
                                moeo = URLEncoder.encode(
                                    binding.etContent.text.toString().trim(),
                                    StandardCharsets.UTF_8.toString()
                                )
                            } catch (e: UnsupportedEncodingException) {
                                e.printStackTrace()
                            }
                        }
                        val map: HashMap<String, Any> = HashMap()
                        map["ptype"] = redType
                        map["count"] = count
                        map["amount"] = money
                        map["memo"] = moeo
                        map["cover"] = ""
                        map["paypassword"] = ""
                        map["im_type"] = 1
                        map["source_id"] = targetId
                        map["count_down"] = 0
                        map["single_price"] = money
                        map["code"] = ""
                        loge("发送红包"+GsonUtil.mapToJsonStr(map).toString())
                        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onSendPacketSubmitMethod(it1) }
                    }else{
                        XPopup.Builder(this@RedExtensionActivity)
                            .popupAnimation(PopupAnimation.ScaleAlphaFromCenter  )
                            .customHostLifecycle(lifecycle)
                            .autoOpenSoftInput(true)
                            .moveUpToKeyboard(true)
                            .dismissOnTouchOutside(false)
                            .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                            .autoOpenSoftInput(true)
                            .asCustom(
                                PayPwdCodePopViiew(this@RedExtensionActivity,5,isSendCode,isSendPassword, object :
                                    PayPwdCodePopViiew.SublickListener{
                                    override fun onAdopt(etCode: String, pwdStr: String) {
                                        loge("验证码="+etCode+"密码="+pwdStr)
                                        showLoading()
                                        var moeo =""
                                        if (TextUtils.isEmpty(binding.etContent.text.toString().trim()))
                                            moeo="恭喜发财 大吉大利"
                                        else{
                                            try {
                                                moeo = URLEncoder.encode(
                                                    binding.etContent.text.toString().trim(),
                                                    StandardCharsets.UTF_8.toString()
                                                )
                                            } catch (e: UnsupportedEncodingException) {
                                                e.printStackTrace()
                                            }
                                        }
                                        val map: HashMap<String, Any> = HashMap()
                                        map["ptype"] = redType
                                        map["count"] = count
                                        map["amount"] = money
                                        map["memo"] = moeo
                                        map["cover"] = ""
                                        map["paypassword"] = ""
                                        map["im_type"] = 1
                                        map["source_id"] = targetId
                                        map["count_down"] = 0
                                        map["single_price"] = money
                                        map["code"] = ""
                                        loge("发送红包"+GsonUtil.mapToJsonStrObjEncryption(map).toString())
                                        GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onSendPacketSubmitMethod(it1) }



                                    }

                                })
                            )

                            .show()

                    }
                }
            }
        }
    }


    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@RedExtensionActivity) {
                dismissLoading()
                showToast(it)
            }
            againLoginMsg.observe(this@RedExtensionActivity) {
                dismissLoading()
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }
            onRedIndexData.observe(this@RedExtensionActivity){
                binding.run {
                    usableHongbao.text= it.data.jifen.toString()


                    //是否需要校验短信验证码
                     isSendCode = it.data.is_need_sms_code
                    //是否需要校验支付密码
                     isSendPassword =it.data.is_need_pay_password
                    service_charge_rate=it.data.service_charge_rate

                    serviceChargeRate.text="注意:发红包需支付${it.data.service_charge_rate}手续费"
                    if(it.data.service_charge_rate>0){
                        serviceChargeRate.visible()
                        tvGao.gone()
                        serviceChargeRate.text = "注意:发红包需支付${(it.data.service_charge_rate*100).toInt()}%手续费"
                    }else{
                        serviceChargeRate.gone()
                        tvGao.visible()
                    }
                    packetMaxCount.text="上限发${it.data.packet_max_count}个红包"
                    maxCount=it.data.packet_max_count
                }
            }

            onSendPacketSubmitData.observe(this@RedExtensionActivity){
                dismissLoading()
                showToast("发送成功")
                finish()
            }
        }
    }

    inner class TextChange() : TextWatcher {
        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
        override fun afterTextChanged(s: Editable) {
            if (redType==1){
                if (!TextUtils.isEmpty( binding.etMoneyNumberAll.text) && !TextUtils.isEmpty(binding.etNum.text)) {
                    binding.tvBtnNext.alpha = 1.0f
                    binding.tvBtnNext.isEnabled=true
                } else {
                    binding.tvBtnNext.alpha = 0.5f
                    binding.tvBtnNext.isEnabled=false
                }
            }else if (redType==2){
                if (!TextUtils.isEmpty( binding.etMoneyNumber.text) && !TextUtils.isEmpty(binding.etNum.text)) {
                    binding.tvBtnNext.alpha = 1.0f
                    binding.tvBtnNext.isEnabled=true
                } else {
                    binding.tvBtnNext.alpha = 0.5f
                    binding.tvBtnNext.isEnabled=false
                }
            }

        }
    }


    // 设置EditText只能输入数字和小数点
    fun setEditTextOnlyDigitsAndDecimal(editText: EditText) {
        val filter = object : InputFilter {
            private val regex = Regex("[0-9.]*")

            override fun filter(
                source: CharSequence?,
                start: Int,
                end: Int,
                dest: Spanned?,
                dstart: Int,
                dend: Int
            ): CharSequence? {
                val input = dest?.subSequence(0, dstart).toString() +
                        source?.subSequence(start, end).toString() +
                        dest?.subSequence(dend, dest.length).toString()

                return if (!regex.matches(input)) {
                    ""
                } else {
                    null
                }
            }
        }

        editText.filters = arrayOf(filter)
    }

    // 设置EditText只能输入数字
    fun setEditTextOnlyDigits(editText: EditText) {
        val filter = object : InputFilter {
            override fun filter(
                source: CharSequence?,
                start: Int,
                end: Int,
                dest: Spanned?,
                dstart: Int,
                dend: Int
            ): CharSequence? {
                for (i in start until end) {
                    if (!Character.isDigit(source?.get(i) ?: ' ')) {
                        return ""
                    }
                }
                return null
            }
        }

        editText.filters = arrayOf(filter)
    }


}